package com.eian.boot.redis.config;

import com.eian.boot.redis.handler.RedisExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.CompositeCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.thread.Threading;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.task.VirtualThreadTaskExecutor;

/**
 * redis配置
 *
 * @author alex.meng
 */
@Slf4j
@AutoConfiguration
@AllArgsConstructor
public class RedisAutoConfiguration {

    @Bean
    public RedissonAutoConfigurationCustomizer redissonCustomizer(ObjectMapper objectMapper, Environment environment) {
        return config -> {
            JsonJacksonCodec jsonCodec = new JsonJacksonCodec(objectMapper);
            CompositeCodec codec = new CompositeCodec(StringCodec.INSTANCE, jsonCodec, jsonCodec);
            config.setUseScriptCache(true)
                    .setCodec(codec);
            if (Threading.VIRTUAL.isActive(environment)) {
                log.info("Redisson 已开启虚拟线程池");
                config.setNettyExecutor(new VirtualThreadTaskExecutor("redisson-handle-"));
            }
            log.info("Redis 初始化完成");
        };
    }

    /**
     * 异常处理器
     */
    @Bean
    public RedisExceptionHandler redisExceptionHandler() {
        return new RedisExceptionHandler();
    }
}
